import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";

class Request {
  private static axiosInstance: AxiosInstance | null = null;
  public static getAxiosInstance(baseURL: string) {
    this.axiosInstance = axios.create({
      baseURL,
      timeout: 6000,
    })
    this.initInterceptors();
    return this.axiosInstance;
  }
  private static initInterceptors() {
    this.axiosInstance && (this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded');
    this.axiosInstance?.interceptors.request.use((config: AxiosRequestConfig) => {
      config.headers && (config.headers['Content-Type'] = 'application/x-www-form-urlencoded');
      return config;
    },
      (error: AxiosError) => {
        return error;
      });
    this.axiosInstance?.interceptors.response.use((response: AxiosResponse) => {
      if (response.status === 200) {
        return response.data;
      } else {
        Request.errorHandler(response);
        return response;
      }
    }, (error: AxiosError) => {
      return error;
    });
  }

  private static errorHandler(error: AxiosError | AxiosResponse) {
    console.log(error);
  }

}

export default Request;